package bma.common.netty.jvm;

import java.util.Iterator;

import org.jboss.netty.channel.Channel;

import bma.common.langutil.core.StringUtil;
import bma.common.langutil.jmshell.JMShellUtil;
import bma.common.langutil.jmshell.Session;
import bma.common.langutil.jmshell.cmdopt.CommandOptionParser;
import bma.common.langutil.jmshell.command.AbstractSimpleCommandProcessor;
import bma.common.netty.jvm.NettyListCommand.NettyInfo;

public class NettyKillCommand extends AbstractSimpleCommandProcessor {

	public NettyKillCommand() {
		super("kill");
		setArgsTips("[ip]");
	}

	@Override
	public CommandOptionParser createCommandOption(Session session) {
		CommandOptionParser r = new CommandOptionParser();
		return r;
	}

	@Override
	public boolean processCommand(Session session, String cmd,
			CommandOptionParser options) {
		String[] args = options.getRemainingArgs();
		if (args != null && args.length > 0) {
			kill(session, args[0]);
			return true;
		}
		session.writeln(getHelp(session));
		return true;
	}

	public void kill(Session s, String ip) {
		NettyInfo info = JMShellUtil.getData(s, NettyListCommand.DATA_KEY,
				NettyInfo.class, false);
		if (info != null) {
			Iterator<Channel> it = info.group.iterator();
			while (it.hasNext()) {
				Channel ch = it.next();
				String rip = ch.getRemoteAddress().toString();
				if (StringUtil.equals(rip, ip)) {
					if (ch.isOpen()) {
						ch.close();
					}
					s.writeln("kill '" + ip + "' done");
					break;
				}
			}
		}
		s.writeln("ERROR: kill '" + ip + "' fail, not found");
	}

}